/**
 * 增强版AI助手
 * 整合统一AI服务，支持多模态交互、个性化设置、上下文记忆
 */

'use client'

import React, { useState, useEffect, useRef, useCallback } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Slider } from "@/components/ui/slider"
import { Switch } from "@/components/ui/switch"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { 
  Bot, 
  Send, 
  X, 
  Mic, 
  MicOff, 
  Camera, 
  Settings, 
  Volume2, 
  VolumeX,
  Maximize2,
  Minimize2,
  RotateCcw,
  Download,
  Upload,
  Image as ImageIcon,
  Eye,
  Scan
} from 'lucide-react'
import { toast } from 'sonner'
import { aiService, AIRequest, AIResponse, AIMessage, AIServiceType, processAIRequest } from '@/lib/aiService'
import { realAIService } from '@/lib/realAIService'

interface EnhancedAIAssistantProps {
  className?: string
  initialServiceType?: AIServiceType
  userId?: string
  context?: {
    hospitalId?: string
    attractionId?: string
    location?: { lng: number; lat: number }
  }
  onNavigateTo?: (location: { lng: number; lat: number }) => void
  onActionTrigger?: (action: any) => void
}

interface AISettings {
  voiceEnabled: boolean
  autoSpeak: boolean
  language: string
  theme: 'light' | 'dark'
  responseSpeed: number
  maxHistoryLength: number
  personalizedResponses: boolean
}

export const EnhancedAIAssistant: React.FC<EnhancedAIAssistantProps> = ({
  className = '',
  initialServiceType = 'hospital',
  userId = 'default',
  context = {},
  onNavigateTo,
  onActionTrigger
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [isExpanded, setIsExpanded] = useState(false)
  const [showSettings, setShowSettings] = useState(false)
  const [activeService, setActiveService] = useState<AIServiceType>(initialServiceType)
  const [messages, setMessages] = useState<AIMessage[]>([])
  const [inputValue, setInputValue] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [isListening, setIsListening] = useState(false)
  const [isRecording, setIsRecording] = useState(false)
  const [selectedImage, setSelectedImage] = useState<string | null>(null)
  const [dragOver, setDragOver] = useState(false)
  
  // AI设置
  const [settings, setSettings] = useState<AISettings>({
    voiceEnabled: false,
    autoSpeak: false,
    language: 'zh-CN',
    theme: 'light',
    responseSpeed: 1,
    maxHistoryLength: 50,
    personalizedResponses: true
  })

  const messagesEndRef = useRef<HTMLDivElement>(null)
  const speechRecognition = useRef<SpeechRecognition | null>(null)
  const speechSynthesis = useRef<SpeechSynthesis | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 服务配置映射
  const serviceConfigs = {
    hospital: {
      name: '医院助手',
      icon: '🏥',
      description: '医疗导航、挂号预约、症状咨询',
      color: 'from-blue-500 to-green-600'
    },
    attraction: {
      name: '景区助手',
      icon: '🗺️',
      description: '景区导览、商铺推荐、设施查询',
      color: 'from-purple-500 to-pink-600'
    },
    advisor: {
      name: '运营顾问',
      icon: '📊',
      description: '数据分析、运营建议、预测预警',
      color: 'from-orange-500 to-red-600'
    },
    medical: {
      name: '医疗咨询',
      icon: '👩‍⚕️',
      description: '专业医疗咨询、用药指导',
      color: 'from-teal-500 to-cyan-600'
    },
    navigation: {
      name: '智能导航',
      icon: '🧭',
      description: '路径规划、实时导航',
      color: 'from-indigo-500 to-blue-600'
    }
  }

  useEffect(() => {
    if (typeof window !== 'undefined') {
      // 初始化语音识别
      if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
        const SpeechRecognition = window.webkitSpeechRecognition || window.SpeechRecognition
        speechRecognition.current = new SpeechRecognition()
        speechRecognition.current.continuous = false
        speechRecognition.current.interimResults = false
        speechRecognition.current.lang = settings.language

        speechRecognition.current.onresult = (event) => {
          const transcript = event.results[0][0].transcript
          setInputValue(transcript)
          setIsListening(false)
          // 自动发送语音输入的消息
          setTimeout(() => handleSendMessage(transcript), 100)
        }

        speechRecognition.current.onerror = () => {
          setIsListening(false)
          toast.error('语音识别失败，请重试')
        }
      }

      // 初始化语音合成
      if ('speechSynthesis' in window) {
        speechSynthesis.current = window.speechSynthesis
      }
    }

    // 加载历史对话
    loadConversationHistory()
  }, [])

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  useEffect(() => {
    // 切换服务时清空对话并发送欢迎消息
    if (isOpen) {
      initializeService()
    }
  }, [activeService, isOpen])

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  // 加载对话历史
  const loadConversationHistory = () => {
    const history = aiService.getConversationHistory(userId)
    setMessages(history.slice(-settings.maxHistoryLength))
  }

  // 初始化服务
  const initializeService = async () => {
    const serviceConfig = serviceConfigs[activeService]
    const welcomeMessage: AIMessage = {
      id: `welcome_${Date.now()}`,
      type: 'assistant',
      content: `您好！我是${serviceConfig.name} ${serviceConfig.icon}\n\n${serviceConfig.description}\n\n请问有什么可以帮您的吗？`,
      timestamp: new Date(),
      serviceType: activeService,
      metadata: {
        suggestions: getInitialSuggestions()
      }
    }
    
    setMessages([welcomeMessage])
  }

  // 获取初始建议
  const getInitialSuggestions = () => {
    switch (activeService) {
      case 'hospital':
        return ['急诊科在哪', '我要挂号', '头痛挂什么科', '药房位置']
      case 'attraction':
        return ['景区介绍', '美食推荐', '卫生间在哪', '有什么活动']
      case 'advisor':
        return ['查看实时数据', '运营分析', '优化建议', '异常预警']
      case 'medical':
        return ['症状咨询', '用药指导', '健康建议', '急诊判断']
      case 'navigation':
        return ['规划路线', '最近设施', '实时导航', '交通状况']
      default:
        return ['帮助', '功能介绍', '使用指南']
    }
  }

  // 处理图像选择
  const handleFileSelect = useCallback((file: File) => {
    if (!file.type.startsWith('image/')) {
      toast.error('请选择图片文件')
      return
    }

    if (file.size > 10 * 1024 * 1024) { // 10MB limit
      toast.error('图片大小不能超过10MB')
      return
    }

    const reader = new FileReader()
    reader.onload = (e) => {
      const base64 = e.target?.result as string
      setSelectedImage(base64)
      toast.success('图片已选择，可以开始分析')
    }
    reader.readAsDataURL(file)
  }, [])

  // 拖拽处理
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(true)
  }, [])

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
  }, [])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
    
    const files = Array.from(e.dataTransfer.files)
    if (files.length > 0) {
      handleFileSelect(files[0])
    }
  }, [handleFileSelect])

  // 发送消息（支持多模态）
  const handleSendMessage = async (message: string = inputValue) => {
    if (!message.trim() && !selectedImage) return

    // 如果有图像，优先使用Ollama Llava3进行多模态分析
    if (selectedImage) {
      const userMessage: AIMessage = {
        id: `user_${Date.now()}`,
        type: 'user',
        content: message || '请分析这张图片',
        timestamp: new Date(),
        serviceType: activeService
      }

      setMessages(prev => [...prev, userMessage])
      setInputValue('')
      setIsLoading(true)

      try {
        // 使用Ollama Llava3进行图像分析
        const messageContent = message ? [
          {
            type: 'text' as const,
            text: message + '（这是一张医疗相关的图片，请提供专业的分析和建议）'
          },
          {
            type: 'image_url' as const,
            image_url: {
              url: selectedImage,
              detail: 'high' as const
            }
          }
        ] : [
          {
            type: 'text' as const,
            text: '请分析这张医疗图片，描述你看到的内容并提供专业建议。'
          },
          {
            type: 'image_url' as const,
            image_url: {
              url: selectedImage,
              detail: 'high' as const
            }
          }
        ]

        const chatMessages = [{
          role: 'user' as const,
          content: messageContent
        }]

        const llavaResponse = await realAIService.chat(chatMessages, {
          provider: 'ollama',
          sessionId: userId,
          temperature: 0.7,
          maxTokens: 4000
        })

        const aiMessage: AIMessage = {
          id: llavaResponse.id,
          type: 'assistant',
          content: llavaResponse.content,
          timestamp: new Date(),
          serviceType: activeService,
          metadata: {
            provider: llavaResponse.provider,
            model: llavaResponse.model,
            hasImage: true,
            processingTime: llavaResponse.metadata?.processingTime
          }
        }

        setMessages(prev => [...prev, aiMessage])
        setSelectedImage(null) // 清除已使用的图片

        // 语音播报
        if (settings.autoSpeak && settings.voiceEnabled) {
          speakText(llavaResponse.content)
        }

        toast.success('图像分析完成！')

      } catch (error) {
        console.error('Llava3图像分析失败:', error)
        const errorMessage: AIMessage = {
          id: `error_${Date.now()}`,
          type: 'assistant',
          content: '抱歉，图像分析服务暂时不可用。请确保Ollama服务正在运行，并且已加载llava模型。',
          timestamp: new Date(),
          serviceType: activeService
        }
        setMessages(prev => [...prev, errorMessage])
        toast.error('图像分析失败，请检查Ollama服务')
      } finally {
        setIsLoading(false)
      }

      return
    }

    // 普通文本消息处理
    const userMessage: AIMessage = {
      id: `user_${Date.now()}`,
      type: 'user',
      content: message,
      timestamp: new Date(),
      serviceType: activeService
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setIsLoading(true)

    try {
      const request: AIRequest = {
        message,
        serviceType: activeService,
        context: {
          userId,
          ...context,
          history: messages.slice(-10) // 提供最近10条历史消息作为上下文
        },
        preferences: {
          language: settings.language,
          responseType: settings.voiceEnabled ? 'multimodal' : 'text',
          maxResponseLength: 500
        }
      }

      const response = await processAIRequest(request)
      
      const aiMessage: AIMessage = {
        id: response.id,
        type: 'assistant',
        content: response.content,
        timestamp: new Date(),
        serviceType: activeService,
        metadata: {
          intent: response.intent,
          suggestions: response.suggestions,
          actions: response.actions,
          context: response.metadata
        }
      }

      setMessages(prev => [...prev, aiMessage])

      // 语音播报
      if (settings.autoSpeak && settings.voiceEnabled) {
        speakText(response.content)
      }

    } catch (error) {
      console.error('AI请求失败:', error)
      const errorMessage: AIMessage = {
        id: `error_${Date.now()}`,
        type: 'assistant',
        content: '抱歉，我遇到了一些问题。请稍后再试。',
        timestamp: new Date(),
        serviceType: activeService
      }
      setMessages(prev => [...prev, errorMessage])
      toast.error('AI服务暂时不可用')
    } finally {
      setIsLoading(false)
    }
  }

  // 语音识别
  const startListening = () => {
    if (speechRecognition.current && settings.voiceEnabled) {
      setIsListening(true)
      speechRecognition.current.start()
      toast.success('正在听取您的语音...')
    } else {
      toast.error('语音功能不可用')
    }
  }

  const stopListening = () => {
    if (speechRecognition.current) {
      speechRecognition.current.stop()
      setIsListening(false)
    }
  }

  // 语音播报
  const speakText = (text: string) => {
    if (speechSynthesis.current && settings.voiceEnabled) {
      const utterance = new SpeechSynthesisUtterance(text)
      utterance.lang = settings.language
      utterance.rate = settings.responseSpeed
      speechSynthesis.current.speak(utterance)
    }
  }

  // 处理文件上传（图像识别）
  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      // 这里可以集成图像识别API
      toast.success('图像上传成功，正在分析...')
      // TODO: 实现图像识别功能
    }
  }

  // 处理建议点击
  const handleSuggestionClick = (suggestion: string) => {
    setInputValue(suggestion)
    setTimeout(() => handleSendMessage(suggestion), 100)
  }

  // 处理动作按钮
  const handleActionClick = (action: any) => {
    switch (action.type) {
      case 'navigate':
        onNavigateTo?.(action.data)
        toast.success('正在为您导航...')
        break
      case 'call':
        if (action.data.phone) {
          window.open(`tel:${action.data.phone}`)
        }
        break
      case 'appointment':
      case 'info':
      case 'emergency':
        onActionTrigger?.(action)
        break
      default:
        toast.info(`执行操作: ${action.label}`)
    }
  }

  // 导出对话历史
  const exportHistory = () => {
    const historyText = messages.map(msg => 
      `[${msg.timestamp.toLocaleString()}] ${msg.type === 'user' ? '用户' : 'AI'}: ${msg.content}`
    ).join('\n')
    
    const blob = new Blob([historyText], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `ai-chat-history-${Date.now()}.txt`
    a.click()
    URL.revokeObjectURL(url)
  }

  // 清空历史
  const clearHistory = () => {
    setMessages([])
    aiService.clearConversationHistory(userId)
    initializeService()
    toast.success('对话历史已清空')
  }

  // 设置面板
  const SettingsPanel = () => (
    <Card className="absolute top-0 left-0 w-full h-full z-50 bg-white">
      <CardHeader>
        <div className="flex justify-between items-center">
          <CardTitle className="text-lg">AI助手设置</CardTitle>
          <Button variant="ghost" size="sm" onClick={() => setShowSettings(false)}>
            <X className="w-4 h-4" />
          </Button>
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 语音设置 */}
        <div className="space-y-2">
          <h4 className="font-medium">语音功能</h4>
          <div className="flex items-center justify-between">
            <span className="text-sm">启用语音</span>
            <Switch 
              checked={settings.voiceEnabled}
              onCheckedChange={(checked) => 
                setSettings(prev => ({ ...prev, voiceEnabled: checked }))
              }
            />
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm">自动播报</span>
            <Switch 
              checked={settings.autoSpeak}
              onCheckedChange={(checked) => 
                setSettings(prev => ({ ...prev, autoSpeak: checked }))
              }
            />
          </div>
        </div>

        {/* 响应速度 */}
        <div className="space-y-2">
          <h4 className="font-medium">响应速度</h4>
          <Slider
            value={[settings.responseSpeed]}
            onValueChange={([value]) => 
              setSettings(prev => ({ ...prev, responseSpeed: value }))
            }
            min={0.5}
            max={2}
            step={0.1}
            className="w-full"
          />
        </div>

        {/* 语言设置 */}
        <div className="space-y-2">
          <h4 className="font-medium">语言</h4>
          <Select 
            value={settings.language}
            onValueChange={(value) => 
              setSettings(prev => ({ ...prev, language: value }))
            }
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="zh-CN">中文</SelectItem>
              <SelectItem value="en-US">English</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* 个性化设置 */}
        <div className="space-y-2">
          <h4 className="font-medium">个性化</h4>
          <div className="flex items-center justify-between">
            <span className="text-sm">个性化响应</span>
            <Switch 
              checked={settings.personalizedResponses}
              onCheckedChange={(checked) => 
                setSettings(prev => ({ ...prev, personalizedResponses: checked }))
              }
            />
          </div>
        </div>

        {/* 操作按钮 */}
        <div className="flex gap-2 pt-4">
          <Button size="sm" variant="outline" onClick={exportHistory}>
            <Download className="w-4 h-4 mr-2" />
            导出记录
          </Button>
          <Button size="sm" variant="outline" onClick={clearHistory}>
            <RotateCcw className="w-4 h-4 mr-2" />
            清空历史
          </Button>
        </div>
      </CardContent>
    </Card>
  )

  if (!isOpen) {
    return (
      <div className={`fixed bottom-4 right-4 z-50 ${className}`}>
        <Button
          onClick={() => setIsOpen(true)}
          size="lg"
          className={`rounded-full w-14 h-14 shadow-lg bg-gradient-to-r ${serviceConfigs[activeService].color} hover:scale-110 transition-all`}
        >
          <Bot className="w-6 h-6" />
        </Button>
      </div>
    )
  }

  const containerClass = isExpanded 
    ? 'fixed inset-4 z-50' 
    : 'fixed bottom-4 right-4 w-96 h-[600px] z-50'

  return (
    <div className={`${containerClass} bg-white rounded-lg shadow-2xl border flex flex-col ${className}`}>
      {/* 头部 */}
      <CardHeader className="pb-3 border-b relative">
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg flex items-center gap-2">
            <span className="text-2xl">{serviceConfigs[activeService].icon}</span>
            <div>
              <div className="font-semibold">AI智能助手</div>
              <div className="text-sm text-gray-500 font-normal">
                {serviceConfigs[activeService].name}
              </div>
            </div>
          </CardTitle>
          
          <div className="flex items-center gap-2">
            {/* 语音状态 */}
            {settings.voiceEnabled && (
              <Badge variant="secondary" className="text-xs">
                {settings.autoSpeak ? <Volume2 className="w-3 h-3" /> : <VolumeX className="w-3 h-3" />}
              </Badge>
            )}
            
            {/* 扩展/收缩 */}
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsExpanded(!isExpanded)}
            >
              {isExpanded ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
            </Button>
            
            {/* 设置 */}
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setShowSettings(!showSettings)}
            >
              <Settings className="w-4 h-4" />
            </Button>
            
            {/* 关闭 */}
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsOpen(false)}
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
        </div>
        
        {/* 服务切换 */}
        <Tabs value={activeService} onValueChange={(value: any) => setActiveService(value)} className="w-full">
          <TabsList className="grid w-full grid-cols-5 h-8 text-xs">
            <TabsTrigger value="hospital" className="px-1">🏥</TabsTrigger>
            <TabsTrigger value="attraction" className="px-1">🗺️</TabsTrigger>
            <TabsTrigger value="advisor" className="px-1">📊</TabsTrigger>
            <TabsTrigger value="medical" className="px-1">👩‍⚕️</TabsTrigger>
            <TabsTrigger value="navigation" className="px-1">🧭</TabsTrigger>
          </TabsList>
        </Tabs>

        {/* 设置面板覆盖 */}
        {showSettings && <SettingsPanel />}
      </CardHeader>

      {!showSettings && (
        <>
          {/* 消息区域 */}
          <CardContent className="flex-1 overflow-y-auto p-4 space-y-3">
            {messages.map((message) => (
              <div
                key={message.id}
                className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}
              >
                <div
                  className={`max-w-[85%] p-3 rounded-lg text-sm ${
                    message.type === 'user'
                      ? 'bg-blue-500 text-white'
                      : 'bg-gray-100 text-gray-800'
                  }`}
                >
                  <div className="whitespace-pre-wrap">{message.content}</div>
                  
                  {/* 建议按钮 */}
                  {message.metadata?.suggestions && message.metadata.suggestions.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                      {message.metadata.suggestions.map((suggestion, index) => (
                        <Button
                          key={index}
                          variant="outline"
                          size="sm"
                          onClick={() => handleSuggestionClick(suggestion)}
                          className="h-6 px-2 text-xs"
                        >
                          {suggestion}
                        </Button>
                      ))}
                    </div>
                  )}
                  
                  {/* 动作按钮 */}
                  {message.metadata?.actions && message.metadata.actions.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                      {message.metadata.actions.map((action, index) => (
                        <Button
                          key={index}
                          variant="secondary"
                          size="sm"
                          onClick={() => handleActionClick(action)}
                          className="h-6 px-2 text-xs"
                        >
                          {action.label}
                        </Button>
                      ))}
                    </div>
                  )}
                  
                  <div className="text-xs opacity-70 mt-1">
                    {message.timestamp.toLocaleTimeString()}
                  </div>
                </div>
              </div>
            ))}
            
            {isLoading && (
              <div className="flex justify-start">
                <div className="bg-gray-100 text-gray-800 p-3 rounded-lg text-sm">
                  <div className="flex items-center gap-2">
                    <div className="w-2 h-2 bg-blue-400 rounded-full animate-bounce" />
                    <div className="w-2 h-2 bg-blue-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }} />
                    <div className="w-2 h-2 bg-blue-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }} />
                    <span>AI思考中...</span>
                  </div>
                </div>
              </div>
            )}
            
            <div ref={messagesEndRef} />
          </CardContent>

          {/* 输入区域 */}
          <div className="p-4 border-t">
            {/* 图片预览区域 */}
            {selectedImage && (
              <div className="mb-3 p-2 border rounded-lg bg-purple-50 border-purple-200">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center space-x-2">
                    <Eye className="w-4 h-4 text-purple-600" />
                    <span className="text-sm text-purple-800 font-medium">已选择图片</span>
                    <Badge variant="secondary" className="bg-purple-100 text-purple-700 text-xs">
                      Llava3分析
                    </Badge>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setSelectedImage(null)}
                    className="h-6 px-2 text-purple-600 hover:text-purple-800"
                  >
                    <X className="w-3 h-3" />
                  </Button>
                </div>
                <img 
                  src={selectedImage} 
                  alt="待分析图片" 
                  className="w-full h-20 object-cover rounded border border-purple-200"
                />
                <p className="text-xs text-purple-600 mt-1">
                  🤖 将使用Ollama Llava3进行专业医疗图像分析
                </p>
              </div>
            )}

            <div className="flex gap-2 mb-2">
              <Input
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                placeholder={selectedImage ? "描述图片或提出问题..." : `向${serviceConfigs[activeService].name}提问...`}
                onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
                disabled={isLoading}
                className="flex-1"
              />
              
              {/* 语音按钮 */}
              {settings.voiceEnabled && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={isListening ? stopListening : startListening}
                  className={isListening ? 'bg-red-100' : ''}
                >
                  {isListening ? <MicOff className="w-4 h-4" /> : <Mic className="w-4 h-4" />}
                </Button>
              )}
              
              {/* 图片上传 */}
              <Button
                variant="outline"
                size="sm"
                onClick={() => fileInputRef.current?.click()}
                className="border-purple-200 text-purple-600 hover:bg-purple-50"
              >
                <Camera className="w-4 h-4" />
              </Button>
              
              {/* 发送按钮 */}
              <Button 
                onClick={() => handleSendMessage()} 
                disabled={isLoading || (!inputValue.trim() && !selectedImage)}
                className={selectedImage ? "bg-purple-600 hover:bg-purple-700 text-white" : `bg-gradient-to-r ${serviceConfigs[activeService].color}`}
              >
                {selectedImage ? <Scan className="w-4 h-4" /> : <Send className="w-4 h-4" />}
              </Button>
            </div>
            
            {/* 状态指示 */}
            <div className="flex items-center justify-between text-xs text-gray-500">
              <span>AI服务: {serviceConfigs[activeService].name} {selectedImage && '+ Llava3图像分析'}</span>
              <span>{messages.length > 0 ? `${messages.length}条消息` : '开始对话'}</span>
            </div>

            {/* Llava3功能提示 */}
            {selectedImage && (
              <div className="mt-2 text-xs text-center text-purple-600 bg-purple-50 rounded p-2">
                <div className="flex items-center justify-center space-x-1">
                  <Bot className="w-3 h-3" />
                  <span>Llava3 13B正在待命，准备分析您的医疗图像</span>
                </div>
              </div>
            )}
          </div>
        </>
      )}
      
      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={(e) => {
          const file = e.target.files?.[0]
          if (file) handleFileSelect(file)
        }}
        className="hidden"
      />
    </div>
  )
}

export default EnhancedAIAssistant